<template>
    <nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" v-link="{name: 'home'}">Vue Demo</a>
            </div>
            <div id="navbar" class="collapse navbar-collapse">
                <ul class="nav navbar-nav" v-for="item in menu">
                    <li :class="{'active': item.isActive}"><a v-link="{path:item.path}">{{item.title}}</a></li>
                </ul>
            </div>
        </div>
    </nav>
</template>

<script>
// 将菜单改造成通用组件
export default {
    data:function(){
        return {
            menu:[{
                title:'Home',
                path:'/home',
                isActive:false
            },{
                title:'Select Demo',
                path:'/select-demo',
                isActive:false
            },{
                title: 'List Demo',
                path: '/list-demo',
                isActive: false
            },{
                title: 'CheckboxDemo',
                path: '/text-demo',
                isActive: false
            },{
                title: 'Vuex Demo',
                path: '/vuex-demo',
                isActive: false
            }]
        }
    },
    created: function(){
        this.updateActive();
    },
    methods: {
        /**
         * 更新菜单的选中状态
         */
        updateActive: function(){
            var hash = location.hash;
            this.menu.forEach((item, index)=>{
                if(item.path === this.$route.path){
                    item.isActive = true;
                }else{
                    item.isActive = false;
                }
            });
        }
    },
    events: {
        'router-change': function(){
            this.updateActive();
        }
    }
}
</script>

<style scoped>

</style>
